package cn.ydxiaoshuai.reptile.aistuido;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.font.TextAttribute;
import java.awt.geom.Ellipse2D;
import java.awt.image.BufferedImage;
import java.net.URL;
import java.net.URLDecoder;
import java.text.AttributedCharacterIterator;
import java.text.AttributedString;

/**
 * Description
 * ProjectName worktools
 * Created by 小帅丶 on 2023-01-03 17:13.
 * Version 1.0
 */

public class AIStudioUtil {
    /**
     * @Description 头像转圆形
     * @param headUrl - 网络图片URL
     * @param widthHeight - 宽高
     * @Author 小帅丶
     * @Date  2023/1/3 17:43
     * @return java.awt.image.BufferedImage
     **/
    public static BufferedImage cutHeadImages(String headUrl,Integer widthHeight) {
        BufferedImage avatarImage = null;
        try {
            avatarImage = ImageIO.read(new URL(headUrl));
            avatarImage = scaleByPercentage(avatarImage, widthHeight,widthHeight);
            int width = avatarImage.getWidth();
            // 透明底的图片
            BufferedImage formatAvatarImage = new BufferedImage(width, width, BufferedImage.TYPE_4BYTE_ABGR);
            Graphics2D graphics = formatAvatarImage.createGraphics();
            //把图片切成一个园
            graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            //留一个像素的空白区域，这个很重要，画圆的时候把这个覆盖
            int border = 1;
            //图片是一个圆型
            Ellipse2D.Double shape = new Ellipse2D.Double(border, border, width - border * 2, width - border * 2);
            //需要保留的区域
            graphics.setClip(shape);
            graphics.drawImage(avatarImage, border, border, width - border * 2, width - border * 2, null);
            graphics.dispose();
            //在圆图外面再画一个圆
            //新创建一个graphics，这样画的圆不会有锯齿
            graphics = formatAvatarImage.createGraphics();
            graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            int border1 = 3;
            //画笔是4.5个像素，BasicStroke的使用可以查看下面的参考文档
            //使画笔时基本会像外延伸一定像素，具体可以自己使用的时候测试
            Stroke s = new BasicStroke(5F, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND);
            graphics.setStroke(s);
            graphics.setColor(Color.WHITE);
            graphics.drawOval(border1, border1, width - border1 * 2, width - border1 * 2);
            graphics.dispose();
            return formatAvatarImage;
        } catch (Exception e) {
            System.out.println("cutHeadImages 出错了======>"+e.getMessage());
        }
        return null;
    }
    /**
     * @Description 头像转圆形
     * @param headUrl - 网络图片URL
     * @Author 小帅丶
     * @Date  2023/1/3 17:43
     * @return java.awt.image.BufferedImage
     **/
    public static BufferedImage cutHeadImages(String headUrl) {
        return cutHeadImages(headUrl,AIStudioConstant.WIDTH_HEIGHT);
    }
    /**
     * @Author 小帅丶
     * @Description 文本填充
     * @Date  2020/11/24 10:32
     * @param g 2d画板
     * @param content  文本内容
     * @param fontFamily  字体
     * @param fontSize  字体大小
     * @param coords  坐标
     * @param isIntercept 是否截取
     * @param interceptLength  截取长度
     * @return java.awt.Graphics2D
     **/
    public static Graphics2D fillTextContent(Graphics2D g, String content, String fontFamily,int fontSize,
                                             Integer []coords,boolean isIntercept, int interceptLength) throws Exception{
        return fillTextContent(g,content,fontFamily,Color.WHITE,fontSize,
                coords,isIntercept,interceptLength);
    }

    /**
     * @Author 小帅丶
     * @Description 文本填充
     * @Date  2020/11/24 10:32
     * @param g 2d画板
     * @param content  文本内容
     * @param fontFamily  字体
     * @param fontSize  字体大小
     * @param fontColor 字体颜色
     * @param coords  坐标
     * @param isIntercept 是否截取
     * @param interceptLength  截取长度
     * @return java.awt.Graphics2D
     **/
    public static Graphics2D fillTextContent(Graphics2D g, String content, String fontFamily,Color fontColor, int fontSize,
                                   Integer []coords,boolean isIntercept, int interceptLength) throws Exception{
        String textContent = URLDecoder.decode(content, "UTF-8");
        if(isIntercept==true&&textContent.length()>interceptLength){
            textContent = textContent.substring(0,interceptLength)+"...";
        }
        AttributedString ats = new AttributedString(textContent);
        // 横批文字填充
        Font font = new Font(fontFamily, Font.PLAIN, fontSize);
        g.setStroke(new BasicStroke(2.0f));
        g.setColor(fontColor);
        g.setFont(font);
        /* 消除java.awt.Font字体的锯齿 */
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
        /* 消除java.awt.Font字体的锯齿 */
        ats.addAttribute(TextAttribute.FONT, font, 0, textContent.length());
        AttributedCharacterIterator iter = ats.getIterator();
        g.drawString(iter,coords[0], coords[1]);
        return g;
    }

    /**
     * 缩小Image，此方法返回源图像按给定宽度、高度限制下缩放后的图像
     *
     * @param inputImage ：压缩后宽度
     *                   ：压缩后高度
     * @throws java.io.IOException return
     */
    public static BufferedImage scaleByPercentage(BufferedImage inputImage, int newWidth, int newHeight) {
        // 获取原始图像透明度类型
        try {
            int type = inputImage.getColorModel().getTransparency();
            int width = inputImage.getWidth();
            int height = inputImage.getHeight();
            // 开启抗锯齿
            RenderingHints renderingHints = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            // 使用高质量压缩
            renderingHints.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
            BufferedImage img = new BufferedImage(newWidth, newHeight, type);
            Graphics2D graphics2d = img.createGraphics();
            graphics2d.setRenderingHints(renderingHints);
            graphics2d.drawImage(inputImage, 0, 0, newWidth, newHeight, 0, 0, width, height, null);
            graphics2d.dispose();
            return img;

        } catch (Exception e) {
            System.out.println("scaleByPercentage 出错了======>"+e.getMessage());
        }
        return null;
    }

    /**
     * 两张图片合并为一张图片
     * @param srcImage 底图
     * @param pendantImage 挂件图
     * @param x 距离右下角的X偏移量
     * @param y 距离右下角的Y偏移量
     * @param alpha  透明度, 选择值从0.0~1.0: 完全透明~完全不透明
     * @return BufferedImage
     * @throws Exception
     */
    public static BufferedImage mergePendant(BufferedImage srcImage, BufferedImage pendantImage, int x, int y, float alpha)throws Exception {
        //创建Graphics2D对象 用在挂件图像对象上绘图
        Graphics2D g2d = srcImage.createGraphics();
        //获取挂件图像的宽高
        int pendantImageWidth = pendantImage.getWidth();
        int pendantImageHeight = pendantImage.getHeight();
        //实现混合和透明效果
        g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,alpha));
        //绘制图像
        g2d.drawImage(pendantImage,x,y,pendantImageWidth,pendantImageHeight,null);
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        return  srcImage;
    }
}
